﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using Cofe.Core.Utils;
using System.ComponentModel.DataAnnotations;


namespace Cofe.Core.Validater
{
    /// <summary>
    /// Extends IPropertyValidater.
    /// </summary>
    public static class IPropertyValidaterExtension
    {
        /// <summary>
        /// Return a list of property validaters for a property.
        /// </summary>
        /// <param name="property"></param>
        /// <returns></returns>
        public static IEnumerable<IPropertyValidator> GetPropertyValidaters(object property)
        {            
              foreach (var attribute in AttributeUtils.GetCustomAttributes(property))
                  if (attribute is IPropertyValidator)
                  yield return (IPropertyValidator)attribute;
        }

        /// <summary>
        /// Use property validaters of a property to validate a value.
        /// </summary>
        /// <param name="property"></param>
        /// <param name="value"></param>
        public static IEnumerable<ValidationResult> GetValidationResult(object property, object value)
        {
            foreach (IPropertyValidator pv in GetPropertyValidaters(property))
            {
                var result = pv.GetValidationResult(value);
                if (result != ValidationResult.Success)
                    yield return result;
            }
        }

    }
}
